//
//  PetViewController.swift
//  PetManager
//
//  Created by 吴翰林 on 2019/11/5.
//  Copyright © 2019 吴翰林. All rights reserved.
//

import UIKit

class PetViewController: UITableViewController, PetDetailViewControllerDelegate, UINavigationControllerDelegate {
    
    var pets: [Pet]
    
    required init?(coder aDecoder: NSCoder) {
        pets = [Pet]()
        
        super.init(coder: aDecoder)
       
        loadTodopets()
    }
    
    func documentsDirectory() -> URL {
        let paths = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)
        return paths[0]
    }
    
    func dataFilePath() -> URL {
        return documentsDirectory().appendingPathComponent("PetManager.plist")
    }
    
    func saveTodopets() {
        let data = NSMutableData()
        let archiver = NSKeyedArchiver(forWritingWith: data)
        archiver.encode(pets, forKey: "Pet")
        archiver.finishEncoding()
        data.write(to: dataFilePath(), atomically: true)
    }
    
    func loadTodopets() {
        let path = dataFilePath()
        if let data = try? Data(contentsOf: path) {
            let unaricher = NSKeyedUnarchiver(forReadingWith: data)
            pets = unaricher.decodeObject(forKey: "Pet") as! [Pet]
            unaricher.finishDecoding()
        }
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
    }
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        tableView.reloadData()
    }
    
    override func viewDidAppear(_ animated: Bool) {
        super.viewDidAppear(animated)
        
        navigationController?.delegate = self
        
       
    }

    // MARK: - Table view data source
    override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return pets.count
    }

    override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cellIdentifier = "Cell"
        var cell = tableView.dequeueReusableCell(withIdentifier: cellIdentifier)
        if cell == nil {
            cell = UITableViewCell(style: .subtitle, reuseIdentifier: cellIdentifier)
        }
        
        let category = pets[indexPath.row]
        cell?.textLabel?.text = category.name
        cell!.imageView!.image = UIImage(named: category.iconName)
        cell?.accessoryType = .detailDisclosureButton
        return cell!
    }
    
//    override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
//        UserDefaults.standard.set(indexPath.row, forKey: "CategoryIndex")
//        
//        let category = pets[indexPath.row]
//        performSegue(withIdentifier: "ShowTodoList", sender: category)
//    }
    
    override func tableView(_ tableView: UITableView, accessoryButtonTappedForRowWith indexPath: IndexPath) {
        let category = pets[indexPath.row]
        let navController = storyboard!.instantiateViewController(withIdentifier: "PetNavigationController") as! UINavigationController
        let controller = navController.topViewController as! PetDetailViewController
        controller.petToEdit = category
        controller.delegate = self
        
        present(navController, animated: true, completion: nil)
    }
    
    override func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCell.EditingStyle, forRowAt indexPath: IndexPath) {
        pets.remove(at: indexPath.row)
        
        let indexPaths = [indexPath]
        tableView.deleteRows(at: indexPaths, with: .automatic)
    }
    
    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
       if segue.identifier == "AddPet" {
            let navController = segue.destination as! UINavigationController
            let controller = navController.topViewController as! PetDetailViewController
            controller.delegate = self
        }
    }
    
    func PetDetailViewController(_ controller: PetDetailViewController, didFinishAdding category: Pet) {
        let newIndex = pets.count
        
        pets.append(category)
        
        let indexPath = IndexPath(row: newIndex, section: 0)
        let indexPaths = [indexPath]
        tableView.insertRows(at: indexPaths, with: .automatic)
        
        dismiss(animated: true, completion: nil)
    }
    
    func PetDetailViewController(_ controller: PetDetailViewController, didFinishEditing category: Pet) {
        
        if let index = pets.firstIndex(of: category) {
            pets[index].name = category.name
            
            let indexPath = IndexPath(row: index, section: 0)
            let cell = tableView.cellForRow(at: indexPath)
            cell?.textLabel?.text = category.name
        }
        
        dismiss(animated: true, completion: nil)
    }
    
    func PetDetailViewController(_ controller: PetDetailViewController, didFinishDelete category: Pet) {
          if let index = pets.firstIndex(of: category){
          pets[index].name = category.name
              
              let indexPath = IndexPath(row: index, section: 0)
              pets.remove(at: indexPath.row)
            tableView.deleteRows(at: [indexPath], with: .left)
          }
          dismiss(animated: true, completion: nil)
          
      }
    
    func navigationController(_ navigationController: UINavigationController, willShow viewController: UIViewController, animated: Bool) {
        if viewController === self {
            UserDefaults.standard.set(-1, forKey: "CategoryIndex")
        }
    }

}
